package com.weibo.db;

import java.util.HashMap;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;


public class WeiBoProvider extends ContentProvider {

	private static final String TAG = "WeiBoProvider";
	private static final String DATABASE_NAME = "weibo.db";
	private static final int DATABASE_VERSION = 3;
	private static final String HOME_TIME_LINE_TABLE_NAME = "home_time_line";
	
	private static final int HOME_TIME_LINE_TABLE = 1;
	private static final int HOME_TIME_LINE_TABLE_ID = 2;
	
	private static final int HOME_TIME_LINE_TABLES = 1;
	 private static HashMap<String, String> sHomeTableProjectionMap;
	
	private static final int CALL_LOG_ID = 1;
    private static final int CALLNUM = 2;
    private static final int CALLNAME = 3;
    private static final int CALLTYPE = 4;
    private static final int CALLTIME = 5;
    
    private DatabaseHelper mOpenHelper;
    private static final UriMatcher sUriMatcher;
    
    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
        	Log.e(TAG, "Database Create!");
            db.execSQL("CREATE TABLE home_time_line ("
            		+HomeTable._ID+" INTEGER primary key,"
            		+"uid INTEGER,"
            		+"favid TEXT,"
            		+"nick TEXT,"
            		+"portrait TEXT," 
            		+"vip INTEGER," 
            		+"content TEXT," 
            		+"rtrootuid INTEGER," 
            		+"rtrootnick TEXT," 
            		+"rtrootvip TEXT," 
            		+"rtreason TEXT," 
            		+"rtnum INTEGER," 
            		+"commentnum INTEGER," 
            		+"time INTEGER," 
            		+"pic TEXT," 
            		+"opic TEXT," 
            		+"src TEXT,"
            		+"rtrootid INTEGER,"
            		+"longitude TEXT,"
            		+"latitude TEXT,"       
            		+"groupid integer"
            		+");");
                 }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS notes");
            onCreate(db);
        }
    }

    
    
	public WeiBoProvider() {
		// TODO Auto-generated constructor stub
	}

	
	@Override
	public boolean onCreate() {
		Log.e(TAG, "Database Create!");
		mOpenHelper = new DatabaseHelper(getContext());
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
		 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
	        qb.setTables(HOME_TIME_LINE_TABLE_NAME);

	        switch (sUriMatcher.match(uri)) {
	        case HOME_TIME_LINE_TABLE:
	            qb.setProjectionMap(sHomeTableProjectionMap);
	            break;

	        case HOME_TIME_LINE_TABLE_ID:
	            qb.setProjectionMap(sHomeTableProjectionMap);
	            qb.appendWhere(HomeTable._ID + "=" + uri.getPathSegments().get(1));
	            break;
	        default:
	            throw new IllegalArgumentException("Unknown URI " + uri);
	        }

	        // If no sort order is specified use the default
	        String orderBy;
	        if (TextUtils.isEmpty(sortOrder)) {
	            orderBy = HomeTable.DEFAULT_SORT_ORDER;
	        } else {
	            orderBy = sortOrder;
	        }

	        // Get the database and run the query
	        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
	        Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);

	        // Tell the cursor what uri to watch, so it knows when its source data changes
	        c.setNotificationUri(getContext().getContentResolver(), uri);
	        return c;
	}

	@Override
	public String getType(Uri uri) {
		 switch (sUriMatcher.match(uri)) {
	        case HOME_TIME_LINE_TABLES:
	            return HomeTable.CONTENT_TYPE;

	        default:
	            throw new IllegalArgumentException("Unknown URI " + uri);
	        }
	}

	@Override
	public Uri insert(Uri uri, ContentValues initialValues) {
		 if (sUriMatcher.match(uri) != HOME_TIME_LINE_TABLES) {
	            throw new IllegalArgumentException("Unknown URI " + uri);
	        }

	        ContentValues values;
	        if (initialValues != null) {
	            values = new ContentValues(initialValues);
	        } else {
	            values = new ContentValues();
	        }


	        // Make sure that the fields are all set
	        


	        


	        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
	        long rowId = db.insert(HOME_TIME_LINE_TABLE_NAME, HomeTable._ID, values);
	        if (rowId > 0) {
	            Uri noteUri = ContentUris.withAppendedId(HomeTable.CONTENT_URI, rowId);
	            getContext().getContentResolver().notifyChange(noteUri, null);
	            return noteUri;
	        }

	        throw new SQLException("Failed to insert row into " + uri);
	}

	@Override
	public int delete(Uri uri, String where, String[] whereArgs) {
		 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
	        int count;
	        switch (sUriMatcher.match(uri)) {
	        case HOME_TIME_LINE_TABLE:
	            count = db.delete(HOME_TIME_LINE_TABLE_NAME, where, whereArgs);
	            break;

	        case HOME_TIME_LINE_TABLE_ID:
	            String callLogId = uri.getPathSegments().get(1);
	            count = db.delete(HOME_TIME_LINE_TABLE_NAME, HomeTable._ID + "=" + callLogId
	                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
	            break;

	        default:
	            throw new IllegalArgumentException("Unknown URI " + uri);
	        }

	        getContext().getContentResolver().notifyChange(uri, null);
	        return count;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
		// TODO Auto-generated method stub
		return 0;
	}
	static {
        sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        sUriMatcher.addURI(HomeTable.AUTHORITY, HOME_TIME_LINE_TABLE_NAME, HOME_TIME_LINE_TABLE);
        sUriMatcher.addURI(HomeTable.AUTHORITY, HOME_TIME_LINE_TABLE_NAME+"/#", HOME_TIME_LINE_TABLE_ID);

        sHomeTableProjectionMap = new HashMap<String, String>();
        sHomeTableProjectionMap.put(HomeTable._ID, HomeTable._ID);
        sHomeTableProjectionMap.put(HomeTable.UID,HomeTable.UID);
        sHomeTableProjectionMap.put(HomeTable.FAVID,HomeTable.FAVID);
        sHomeTableProjectionMap.put(HomeTable.NICK,HomeTable.NICK);
        sHomeTableProjectionMap.put(HomeTable.PORTRAIT,HomeTable.PORTRAIT);
        sHomeTableProjectionMap.put(HomeTable.VIP,HomeTable.VIP);
        sHomeTableProjectionMap.put(HomeTable.CONTENT,HomeTable.CONTENT);
        sHomeTableProjectionMap.put(HomeTable.RTROOTUID,HomeTable.RTROOTUID);
        sHomeTableProjectionMap.put(HomeTable.RTROOTNICK,HomeTable.RTROOTNICK);
        sHomeTableProjectionMap.put(HomeTable.RTROOTVIP,HomeTable.RTROOTVIP);
        sHomeTableProjectionMap.put(HomeTable.RTREASON,HomeTable.RTREASON);
        sHomeTableProjectionMap.put(HomeTable.RTNUM,HomeTable.RTNUM);
        sHomeTableProjectionMap.put(HomeTable.COMMENTNUM,HomeTable.COMMENTNUM);
        sHomeTableProjectionMap.put(HomeTable.TIME,HomeTable.TIME);
        sHomeTableProjectionMap.put(HomeTable.PIC,HomeTable.PIC);
        sHomeTableProjectionMap.put(HomeTable.OPIC,HomeTable.OPIC);
        sHomeTableProjectionMap.put(HomeTable.SRC,HomeTable.SRC);
        sHomeTableProjectionMap.put(HomeTable.RTROOTID,HomeTable.RTROOTID);
        sHomeTableProjectionMap.put(HomeTable.LONGITUDE,HomeTable.LONGITUDE);
        sHomeTableProjectionMap.put(HomeTable.LATITUDE,HomeTable.LATITUDE);
        sHomeTableProjectionMap.put(HomeTable.GROUPID,HomeTable.GROUPID);
    }
}
